//
//  BIDMemberListViewController.m
//  zhangqitong
//
//  Created by mal on 15/12/9.
//  Copyright © 2015年 mal. All rights reserved.
//

#import "BIDMemberListViewController.h"
#import "BIDMemberListHeaderView.h"
#import "BIDSectionHeaderForMemberListView.h"
#import "BIDMemberCell.h"
#import <SDWebImage/UIImageView+WebCache.h>

#import "BIDNode.h"
//获取所有人员
static NSString *addressBookURL = @"userAndroid!gainDepUsers.action";
//部门列表
static NSString *departmentListURL = @"userAndroid!getDepartmentList2.action";
//职务列表
static NSString *positionListURL = @"userAndroid!getPostList.action";

@interface BIDMemberListViewController ()<BIDBaseListViewDelegate, BIDMemberCellDelegate>
{
    NSMutableArray *_originArr;
    //保存section header选中状态的数组(整个部门是否全部选中)
    NSMutableArray *_sectionChooseFlagArr;
    //该部门有人员被选中，则需要把标记置为1，否则为0
    NSMutableArray *_memberChoosedInSectionFlagArr;
    //用于保存cell的选中状态的二维数组
    NSMutableArray *_flagArr;
    //section是否展开的状态
    NSMutableArray *_expandStateArr;
    //部门数组
    NSMutableArray *_departmentArr;
    //
    BIDMemberListHeaderView *_tableHeaderView;
    //是否需要全部选中选项打钩
    BOOL _bAllChoose;
    //根节点
    BIDNode *_rootNode;
    //
    NSArray *_srcArr;
}
@end

@implementation BIDMemberListViewController
@synthesize chooseType;
@synthesize bShowAllOption;
@synthesize delegate;
@synthesize rightNavigationItemTitle;
@synthesize choosedMemberIdArr;
@synthesize choosedMemberNameArr;
@synthesize dataSourceArr;
@synthesize sectionArr;
@synthesize bRegister;
@synthesize sectionHeaderBgColorArr;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"人员列表";
    // Do any additional setup after loading the view.
    //
    [self.myTableView hasNoMoreData];
    [self.myTableView setBackgroundColor:[UIColor clearColor]];
    _originArr = [NSMutableArray array];
    dataSourceArr = [NSMutableArray array];
    _sectionChooseFlagArr = [NSMutableArray array];
    _memberChoosedInSectionFlagArr = [NSMutableArray array];
    sectionArr = [NSMutableArray array];
    _flagArr = [NSMutableArray array];
    _expandStateArr = [NSMutableArray array];
    //随机背景色数组
    sectionHeaderBgColorArr = [NSMutableArray array];
    //
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确认" style:UIBarButtonItemStylePlain target:self action:@selector(confirmHandler)];
    //
    [self getMemberList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//
- (void)confirmHandler
{
    NSMutableArray *idArr = [NSMutableArray array];
    NSMutableArray *nameArr = [NSMutableArray array];
    NSArray *arr = [_rootNode getAllRelatedChildNode];
    [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
        BIDNode *node = (BIDNode *)obj;
        if(node.isPerson && node.chooseStatus==CHOOSE_STATUS_CHOOSE)
        {
            [idArr addObject:node.nodeID];
            NSDictionary *dic = node.data;
            [nameArr addObject:dic[@"name"]];
        }
    }];
    [delegate getChoosedMember:[idArr componentsJoinedByString:@","] andNames:[nameArr componentsJoinedByString:@","]];
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *本地数据库有数据时从本地加载、没有数据则从后台获取并存入数据库中
 */
- (void)getMemberList
{
    BIDDatabaseManager *db = [BIDDatabaseManager getInstance];
    [db openDB];
    NSArray *arr = [db queryFromTable:@"user" fields:@[@"id", @"parentId", @"name", @"isPerson"] condition:nil index:-1];
    [db closeDB];
    if(ISNULL(arr) || arr.count==0)
    {
        //从后台获取
        [self loadData];
    }
    else
    {
        _srcArr = [[NSArray alloc] initWithArray:arr];
        [self showSpinnerView];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self transformDataFrom:_srcArr];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideSpinnerView];
                [self.myTableView reloadData];
            });
        });
    }
}
    
/**
 从后台获取所有用户
 */
- (void)loadData
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], addressBookURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"userId=%@", [AppDelegate getUserId]];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(id responseObj, NSString *errMsg){
        if([responseObj isKindOfClass:[NSArray class]])
        {
            NSArray *arr = (NSArray*)responseObj;
            _srcArr = [[NSArray alloc] initWithArray:arr];
            [self showSpinnerView];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [self storeDataToDB:_srcArr];
                [self transformDataFrom:arr];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self hideSpinnerView];
                    [self.myTableView reloadData];
                });
            });
        }
    }];
}
//
/**
 *  把人员数据存入数据库中
 */
- (void)storeDataToDB:(NSArray*)srcArr
{
    if(srcArr && srcArr.count>0)
    {
        BIDDatabaseManager *db = [BIDDatabaseManager getInstance];
        [db openDB];
        //先删除表中所有数据
        BOOL bFlag = [db deleteAllFromTable:@"user"];
        NSLog(@"delete from table(user) %d", bFlag?1:0);
        NSArray *memberArr = srcArr;
        for(int j=0; j<memberArr.count; j++)
        {
            NSDictionary *memberDic = memberArr[j];
            //
            BOOL bFlag = [db insertRecordToTable:@"user" content:@{@"id":ANY2NSSTRING(memberDic[@"id"]), @"parentId":ANY2NSSTRING(memberDic[@"parentId"]), @"name":memberDic[@"name"], @"isPerson":memberDic[@"isPerson"]}];
            NSLog(@"insert %@ to 'user' %d", memberDic[@"name"], bFlag?1:0);
        }
        [db closeDB];
    }
}

//
- (void)transformDataFrom:(NSArray *)srcArr
{
    if(srcArr && srcArr.count>0)
    {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.parentId=%@", @""];
        NSArray *filteredArr = [srcArr filteredArrayUsingPredicate:predicate];
        if(filteredArr.count > 0)
        {
            NSDictionary *tempDic = filteredArr[0];
            BIDNode *node = [[BIDNode alloc] init];
            _rootNode = node;
            node.nodeID = ANY2NSSTRING(tempDic[@"id"]);
            node.level = 0;
            node.isExpand = YES;
            node.parentID = @"";
            node.parentNode = nil;
            NSNumber *value = tempDic[@"isPerson"];
            node.isPerson = [value intValue]==1 ? YES : NO;
            node.data = [[NSDictionary alloc] initWithDictionary:tempDic];
            [self getChildrenByNode:node];
            //
            [self.dataSourceArr addObject:node];
            for(BIDNode *tempNode in node.childArr)
            {
                [self.dataSourceArr addObject:tempNode];
            }
        }
    }
}
- (NSArray *)getChildrenByNode:(BIDNode *)parentNode
{
    NSString *parentID = parentNode.nodeID;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.parentId=%@ OR self.parentId=%d", parentID, [parentID intValue]];
    NSArray *filteredArr = [_srcArr filteredArrayUsingPredicate:predicate];
    if(filteredArr && filteredArr.count>0)
    {
        for(NSDictionary *tempDic in filteredArr)
        {
            BIDNode *node = [[BIDNode alloc] init];
            node.level = parentNode.level + 1;
            node.data = [[NSDictionary alloc] initWithDictionary:tempDic];
            node.nodeID = ANY2NSSTRING(tempDic[@"id"]);
            node.parentNode = parentNode;
            node.parentID = parentNode.nodeID;
            NSNumber *value = tempDic[@"isPerson"];
            node.isPerson = [value intValue]==1 ? YES : NO;
            NSArray *arr = [self getChildrenByNode:node];
            node.isLeaf = arr.count>0 ? NO : YES;
            [parentNode.childArr addObject:node];
        }
    }
    return filteredArr;
}
    
/**
 更新数据源
 */
- (void)updateDataSourceBy:(BIDNode *)node atIndex:(NSUInteger)index
{
    if(node.isPerson) return;
    NSArray *arr = nil;
    if(node.isExpand)//已展开
    {
        node.isExpand = NO;
        arr = node.childArr;
        if(arr.count>0)
        {
            NSArray *arr = [node getAllRelatedChildNode];
            for(BIDNode *node in arr)
            {
                node.isExpand = NO;
            }
            [self.dataSourceArr removeObjectsInArray:arr];
            [self.myTableView reloadData];
        }
    }
    else//还未展开
    {
        node.isExpand = YES;
        arr = node.childArr;
        if(arr.count>0)
        {
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(index+1, arr.count)];
            [self.dataSourceArr insertObjects:arr atIndexes:indexSet];
            [self.myTableView reloadData];
        }
    }
}

- (void)reset
{
    dataSourceArr = [NSMutableArray array];
    _srcArr = [NSMutableArray array];
}

#pragma mark - BIDMemberCellDelegate
- (void)selectAtIndexPath:(NSIndexPath *)indexPath selected:(BOOL)bSelect
{
    NSUInteger row = indexPath.row;
    BIDNode *node = self.dataSourceArr[row];
    if(bSelect)
    {
        [node chooseNode];
    }
    else
    {
        [node inchooseNode];
    }
    [self.myTableView reloadData];
}

#pragma mark - UITableViewDelegate
- (void)refresh
{
    NSMutableArray *indexPathArr = [NSMutableArray array];
    for(int i=0; i<dataSourceArr.count; i++)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        [indexPathArr addObject:indexPath];
    }
    [self.myTableView beginUpdates];
    [self.myTableView deleteRowsAtIndexPaths:indexPathArr withRowAnimation:UITableViewRowAnimationAutomatic];
    [self reset];
    [self.myTableView endUpdates];
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArr.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    NSUInteger row = indexPath.row;
    BIDNode *node = dataSourceArr[row];
    if(!bRegister)
    {
        bRegister = YES;
        UINib *nib = [UINib nibWithNibName:@"BIDMemberCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
    }
    BIDMemberCell *memberCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    memberCell.delegate = self;
    memberCell.chooseType = self.chooseType;
    memberCell.indexPath = indexPath;
    //memberCell.isChoose = node.isChoose;
    memberCell.chooseStatus = node.chooseStatus;
    memberCell.nameLabel.text = node.data[@"name"];
    memberCell.selectionStyle = UITableViewCellSelectionStyleNone;
    if(node.isPerson)
    {
        memberCell.imgView.image = nil;
    }
    else
    {
        if(node.isExpand)
        {
            memberCell.imgView.image = [UIImage imageNamed:@"expand.png"];
        }
        else
        {
            memberCell.imgView.image = [UIImage imageNamed:@"unexpand.png"];
        }
    }
    memberCell.stepWidth = 26;
    memberCell.stepLevel = node.level;
    memberCell.isPerson = node.isPerson;
    memberCell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell = memberCell;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger row = indexPath.row;
    BIDNode *node = self.dataSourceArr[row];
    if(node.isPerson)
    {
    }
    else
    {
        [self updateDataSourceBy:node atIndex:row];
    }
}

@end
